<template>
  <div class="exercise-detail-page">
    <van-nav-bar title="题目详情" left-text="返回" left-arrow @click-left="router.back()" />
    <div class="exercise-content">
      <div class="question" v-html="exercise?.content"></div>
      <div class="divider"></div>
      <div class="compiler-section">
        <div class="compiler-header">
          <span>在线编译器</span>
          <!-- 新增：代码语言选择 -->
          <van-dropdown-menu>
            <van-dropdown-item v-model="selectedLanguage" :options="languageOptions" />
          </van-dropdown-menu>
          <van-button size="small" @click="runCode" :loading="loading">运行</van-button>
          <van-button size="small" @click="judgeAnswer" :disabled="loading">判题</van-button>
        </div>
        <van-field
          v-model="sourceCode"
          type="textarea"
          rows="10"
          autosize
          placeholder="请在此输入代码"
        />
        <div class="input-area">
          <span>输入：</span>
          <van-field v-model="stdin" type="textarea" rows="2" autosize placeholder="输入数据" />
        </div>
        <div class="output-area">
          <span>输出：</span>
          <pre><code>{{ output }}</code></pre>
        </div>
        <div v-if="judgeResult" class="judge-result" :class="{ correct: judgeResult === '正确', wrong: judgeResult === '错误' }">
          判题结果：{{ judgeResult }}
        </div>
      </div>
    </div>
    <!-- 替换原有的 dify-chat-float 部分 -->
    <div
      class="ai-help-float"
      :style="{ right: chatPosition.x + 'px', bottom: chatPosition.y + 'px' }"
      @mousedown="startDrag"
      @touchstart="startDrag"
    >
      <div 
        class="ai-help-btn"
        @click="showAiOptions = true"
      >
        <van-icon name="bulb-o" />
      </div>

      <van-action-sheet
        v-model:show="showAiOptions"
        title="选择功能"
        class="ai-options-sheet"
        :close-on-click-overlay="true"
        :safe-area-inset-bottom="true"
      >
        <div class="options-grid">
          <div 
            v-for="option in aiOptions" 
            :key="option.value" 
            class="option-item"
            @click="handleAiOptionSelect(option)"
            :class="{ 'chat-option': option.value === 'chat' }"
          >
            <div class="option-icon" :style="{ color: option.color }">
              <van-icon :name="option.icon" />
            </div>
            <div class="option-content">
              <div class="option-title">{{ option.name }}</div>
              <div class="option-desc">{{ option.desc }}</div>
            </div>
          </div>
        </div>
      </van-action-sheet>

      <!-- AI聊天窗口 -->
      <transition name="slide-up">
        <div v-if="showChat" class="ai-chat-window">
          <div class="chat-header">
            <span>{{ currentAction?.name || 'AI助手' }}</span>
            <van-icon name="cross" @click="closeChat" />
          </div>
          <div class="chat-messages" ref="chatMessagesRef">
            <div v-for="(message, index) in messages" 
                :key="index" 
                :class="['message', message.role === 'user' ? 'user-message' : 'ai-message']"
            >
              <template v-if="message.role === 'assistant'">
                <div class="message-avatar">
                  <van-icon name="manager" />
                </div>
                <div class="message-content">
                  <p v-html="message.content"></p>
                  <div v-if="message.showLoadingState" class="loading-tip">
                    正在思考中...
                  </div>
                </div>
              </template>
              <template v-else>
                <div class="message-content">
                  <p v-html="message.content"></p>
                </div>
                <div class="message-avatar">
                  <van-icon name="contact" />
                </div>
              </template>
            </div>
          </div>
          <div class="chat-input">
            <van-field
              v-model="inputMessage"
              rows="1"
              autosize
              type="textarea"
              placeholder="输入消息..."
              class="message-field"
            >
              <template #button>
                <van-button 
                  size="small" 
                  type="primary" 
                  class="send-button" 
                  :loading="loading"
                  :disabled="!inputMessage.trim()"
                  @click="sendMessage"
                >发送</van-button>
              </template>
            </van-field>
          </div>
        </div>
      </transition>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, watch, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { showToast, showLoadingToast } from 'vant'
import { executeCode, LANGUAGE_CONFIG } from '@/api/jdoodle'
import { createChatMessage } from '@/api/dify'

// 题库数据（与列表页保持一致，可抽离到单独文件）
const exercises = [
  // ...与ExerciseList.vue相同的题库数据...
  {
    id: 1,
    title: '两数之和',
    desc: '给定两个整数，输出它们的和。',
    category: '基础语法',
    content: `### 题目描述
给定两个整数 a 和 b，输出它们的和。

**输入格式**
两个整数 a 和 b，空格分隔。

**输出格式**
一个整数，表示 a+b 的结果。

**样例输入**
\`\`\`
3 5
\`\`\`

**样例输出**
\`\`\`
8
\`\`\`
`,
    judge: (input, output) => {
      const [a, b] = input.trim().split(/\s+/).map(Number)
      return String(a + b) === output.trim()
    },
    defaultInput: '3 5',
    defaultAnswer: '8'
  },
  {
    id: 2,
    title: '判断回文字符串',
    desc: '判断输入的字符串是否为回文。',
    category: '字符串',
    content: `### 题目描述
输入一个字符串，判断它是否为回文字符串（正着反着都一样）。

**输入格式**
一行字符串。

**输出格式**
如果是回文输出 "Yes"，否则输出 "No"。

**样例输入**
\`\`\`
abcba
\`\`\`

**样例输出**
\`\`\`
Yes
\`\`\`
`,
    judge: (input, output) => {
      const s = input.trim()
      const isPal = s === s.split('').reverse().join('')
      return (isPal ? 'Yes' : 'No') === output.trim()
    },
    defaultInput: 'abcba',
    defaultAnswer: 'Yes'
  }
]

const languageOptions = [
  { text: 'JavaScript (Node.js)', value: 'javascript' },
  { text: 'Python 3', value: 'python' },
  { text: 'Java', value: 'java' },
  { text: 'C++', value: 'cpp' },
  { text: 'Go', value: 'go' }
]

const route = useRoute()
const router = useRouter()
const exercise = computed(() => exercises.find(e => String(e.id) === String(route.params.id)))

const selectedLanguage = ref('javascript')
const sourceCode = ref('')
const stdin = ref('')
const output = ref('')
const isLoading = ref(false)
const judgeResult = ref('')

const runCode = async () => {
  if (!sourceCode.value.trim()) {
    showToast('请输入代码')
    return
  }
  isLoading.value = true
  output.value = ''
  judgeResult.value = ''
  const toast = showLoadingToast({ message: '编译执行中...', forbidClick: true })
  try {
    const result = await executeCode(selectedLanguage.value, sourceCode.value, stdin.value)
    if (result.success) {
      output.value = result.output
    } else {
      output.value = `执行错误: ${result.error}`
    }
  } catch (err) {
    output.value = '运行出错: ' + err.message
  } finally {
    isLoading.value = false
    toast.close()
  }
}

const judgeAnswer = () => {
  if (!exercise.value) return
  if (!output.value) {
    showToast('请先运行代码')
    return
  }
  // 只取输出的第一行
  const userOut = output.value.split('\n')[0].trim()
  const ok = exercise.value.judge(stdin.value, userOut)
  judgeResult.value = ok ? '正确' : '错误'
}

// Dify 聊天按钮与窗口逻辑
const showChat = ref(false)
const chatMessagesRef = ref(null)
const inputMessage = ref('')
const messages = ref([])
const loading = ref(false)
const currentAction = ref(null)
const conversationId = ref(null) // 添加conversationId来保持对话上下文

const chatPosition = ref({ x: 24, y: 24 }) // 距离右下角的距离(px)
let dragging = false
let dragStart = { x: 0, y: 0 }
let posStart = { x: 0, y: 0 }

const toggleChat = () => {
  showChat.value = !showChat.value
}

const startDrag = (e) => {
  dragging = true
  if (e.type === 'touchstart') {
    dragStart = { x: e.touches[0].clientX, y: e.touches[0].clientY }
  } else {
    dragStart = { x: e.clientX, y: e.clientY }
  }
  posStart = { ...chatPosition.value }
  document.addEventListener('mousemove', onDrag)
  document.addEventListener('mouseup', stopDrag)
  document.addEventListener('touchmove', onDrag)
  document.addEventListener('touchend', stopDrag)
}

const onDrag = (e) => {
  if (!dragging) return
  
  let clientX, clientY
  if (e.type.startsWith('touch')) {
    clientX = e.touches[0].clientX
    clientY = e.touches[0].clientY
  } else {
    clientX = e.clientX
    clientY = e.clientY
  }
  const dx = dragStart.x - clientX
  const dy = dragStart.y - clientY
  
  const minX = 12, minY = 12
  const maxX = window.innerWidth - 56
  const maxY = window.innerHeight - 56
  let newX = Math.min(Math.max(posStart.x + dx, minX), maxX)
  let newY = Math.min(Math.max(posStart.y + dy, minY), maxY)
  chatPosition.value = { x: newX, y: newY }
}

const stopDrag = () => {
  dragging = false
  document.removeEventListener('mousemove', onDrag)
  document.removeEventListener('mouseup', stopDrag)
  document.removeEventListener('touchmove', onDrag)
  document.removeEventListener('touchend', stopDrag)
}

onUnmounted(() => {
  stopDrag()
})

const showAiOptions = ref(false)

const aiOptions = [
  { 
    name: '题目翻译', 
    value: 'translate',
    icon: 'orders-o', // 修改为 orders-o 图标，这是一个文档相关的图标
    desc: '将题目翻译成中文',
    color: '#1989fa'
  },
  { 
    name: '题目解读', 
    value: 'interpret',
    icon: 'description',
    desc: '理解题目要求和考点',
    color: '#07c160'
  },
  { 
    name: '代码分析', 
    value: 'analyze',
    icon: 'search',
    desc: '分析代码逻辑和优化建议',
    color: '#ee0a24'
  },
  { 
    name: '反思报告', 
    value: 'reflect',
    icon: 'notes-o',
    desc: '总结解题思路和经验',
    color: '#ff976a'
  },
  { 
    name: '自由聊天', 
    value: 'chat',
    icon: 'chat-o',
    desc: '与AI助手自由交流',
    color: '#7232dd'
  }
]

const handleAiOptionSelect = async (action) => {
  currentAction.value = action
  showAiOptions.value = false
  showChat.value = true
  messages.value = []

  if (action.value === 'chat') {
    // 自由聊天模式显示开场白
    messages.value.push({
      role: 'assistant',
      content: '你好，我是你的AI助手，有什么可以帮你的吗？',
      showLoadingState: false
    })
    conversationId.value = null
    return
  }

  // 其他功能保持原有逻辑
  let prompt = ''
  switch(action.value) {
    case 'translate':
      prompt = `题目翻译：\n${exercise.value?.content}`
      break
    case 'interpret':
      prompt = `题目解读：\n${exercise.value?.content}`
      break
    case 'analyze':
      prompt = `代码分析：\n题目：${exercise.value?.content}\n代码：\n${sourceCode.value}`
      break
    case 'reflect':
      prompt = `请对我解决这道题目的思路和代码进行总结，并给出改进建议：\n题目：${exercise.value?.content}\n我的代码：\n${sourceCode.value}`
      break
  }
  
  if (prompt) {
    const aiMessage = {
      role: 'assistant',
      content: '正在思考中...',
      showLoadingState: true // 修改：初始设置为true
    }
    messages.value.push(aiMessage)
    
    try {
      await createChatMessage(prompt, conversationId.value, [], (data) => {
        if (data.conversation_id && !conversationId.value) {
          conversationId.value = data.conversation_id
        }
        if (data.event === 'message_replace' || data.event === 'agent_message') {
          aiMessage.content = data.answer
          scrollToBottom()
        } else if (data.event === 'message_end') {
          aiMessage.showLoadingState = false // 确保在完成时设置为false
          aiMessage.content = data.answer || aiMessage.content
          scrollToBottom()
        }
      })
    } catch (err) {
      // 发生错误时也要清除loading状态
      messages.value.pop() // 移除当前的loading消息
      messages.value.push({
        role: 'assistant',
        content: '抱歉，AI助手遇到了问题，请稍后再试。',
        showLoadingState: false
      })
    }
  }
}

const closeChat = () => {
  showChat.value = false
  currentAction.value = null
  inputMessage.value = ''
  messages.value = []
}

const sendMessage = async () => {
  if (!inputMessage.value.trim() || loading.value) return
  
  messages.value.push({
    role: 'user',
    content: inputMessage.value
  })
  
  const userMessage = inputMessage.value
  inputMessage.value = ''
  loading.value = true
  
  try {
    messages.value.push({
      role: 'assistant',
      content: '',
      showLoadingState: true
    })
    
    await createChatMessage(userMessage, conversationId.value, [], (data) => {
      const lastMessage = messages.value[messages.value.length - 1]
      if (data.conversation_id && !conversationId.value) {
        // 保存新的会话ID
        conversationId.value = data.conversation_id
      }
      if (data.event === 'message_replace' || data.event === 'agent_message') {
        lastMessage.content = data.answer
        scrollToBottom()
      } else if (data.event === 'done') {
        lastMessage.showLoadingState = false
        lastMessage.content = data.answer || lastMessage.content
        scrollToBottom()
      }
    })
  } catch (err) {
    const errorMessage = err.message.includes('当前对话尚未完成') 
      ? '请等待当前对话完成' 
      : 'AI助手遇到了问题，请稍后再试'
    
    messages.value.pop() // 移除助手的消息
    messages.value.push({
      role: 'assistant',
      content: errorMessage,
      showLoadingState: false
    })
  } finally {
    loading.value = false
    scrollToBottom()
  }
}

const scrollToBottom = async () => {
  await nextTick()
  const messagesEl = chatMessagesRef.value
  if (messagesEl) {
    messagesEl.scrollTop = messagesEl.scrollHeight
  }
}

onMounted(() => {
  // 监听消息变化，自动滚动到底部
  watch(messages, () => {
    scrollToBottom()
  })
})
</script>

<style scoped>
.exercise-detail-page {
  min-height: 100vh;
  background: #f7f8fa;
  padding-bottom: 80px; /* 防止底部内容被遮挡 */
  position: relative;
}
.exercise-content {
  padding: 16px;
}
.question {
  background: #fff;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 12px;
  font-size: 15px;
}
.divider {
  height: 1px;
  background: #eee;
  margin: 12px 0;
}
.compiler-section {
  background: #fff;
  border-radius: 8px;
  padding: 16px;
}
.compiler-header {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 8px;
}
.input-area, .output-area {
  margin: 8px 0;
}
.judge-result {
  margin-top: 8px;
  font-weight: bold;
}
.judge-result.correct {
  color: #07c160;
}
.judge-result.wrong {
  color: #ee0a24;
}
.ai-help-float {
  position: fixed;
  z-index: 9999;
  user-select: none;
  right: 0;
  bottom: 0;
}

.ai-help-btn {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  background: #1C64F2;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 2px 8px rgba(0,0,0,0.18);
  cursor: grab;
  transition: box-shadow 0.2s;
  position: absolute;
  right: 16px;
  bottom: 16px;
  z-index: 2;
}

.ai-help-btn:active {
  box-shadow: 0 4px 16px rgba(0,0,0,0.25);
}

.help-menu-popup {
  width: 100%;
  height: auto;
}

.help-menu {
  padding: 16px;
}

.help-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 12px;
}

.help-items {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.help-item {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
}

.dify-chat-window {
  position: fixed;
  left: 0;
  top: 0;
  width: 100vw;
  height: 75vh;
  background: #fff;
  border-radius: 0 0 16px 16px;
  box-shadow: 0 2px 16px rgba(0,0,0,0.18);
  display: flex;
  flex-direction: column;
  overflow: hidden;
  z-index: 1999;
}

.dify-chat-header {
  height: 40px;
  background: #f5f5f5;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 16px;
  font-weight: 500;
  border-bottom: 1px solid #eee;
}

.dify-chat-iframe {
  flex: 1;
  width: 100%;
  border: none;
  min-height: 0;
}

@media (max-width: 500px) {
  .dify-chat-window {
    border-radius: 0 0 8px 8px;
  }
}

.fade-enter-active, .fade-leave-active {
  transition: opacity 0.2s;
}
.fade-enter-from, .fade-leave-to {
  opacity: 0;
}

.ai-options-sheet {
  z-index: 2000 !important;
  .van-action-sheet__header {
    font-weight: bold;
    color: #333;
    font-size: 16px;
    padding: 16px;
    position: relative;
    text-align: center;
    
    &::after {
      content: '';
      position: absolute;
      bottom: 0;
      left: 16px;
      right: 16px;
      height: 1px;
      background: #f5f5f5;
    }
  }
  
  .options-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 12px;
    padding: 16px;
  }

  .option-item {
    background: #f8fafc;
    border-radius: 12px;
    padding: 16px;
    display: flex;
    align-items: center;
    gap: 12px;
    transition: all 0.3s ease;
    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.03);
    border: 1px solid rgba(0, 0, 0, 0.04);

    &:active {
      background: #f1f5f9;
      transform: scale(0.98);
    }

    &.chat-option {
      grid-column: span 2;
      background: linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%);
      
      .option-icon {
        background: rgba(25, 137, 250, 0.1);
      }
    }

    .option-icon {
      width: 36px;
      height: 36px;
      display: flex;
      align-items: center;
      justify-content: center;
      color: #1989fa;
      background: rgba(25, 137, 250, 0.06);
      border-radius: 10px;
      font-size: 20px;
    }

    .option-content {
      flex: 1;

      .option-title {
        font-size: 15px;
        font-weight: 600;
        color: #1c1c1e;
        margin-bottom: 4px;
      }

      .option-desc {
        font-size: 12px;
        color: #8e8e93;
        line-height: 1.4;
      }
    }
  }
}

.van-action-sheet {
  z-index: 2001 !important;
}

.ai-chat-window {
  position: fixed;
  left: 0;
  bottom: 0;
  width: 100%;
  height: 75vh;
  background: #fff;
  box-shadow: 0 2px 16px rgba(0,0,0,0.18);
  display: flex;
  flex-direction: column;
  z-index: 2000;
}

.chat-header {
  height: 40px;
  background: #f5f5f5;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 16px;
  font-weight: 500;
  border-bottom: 1px solid #eee;
}

.chat-messages {
  flex: 1;
  padding: 16px;
  overflow-y: auto;
}

.message {
  display: flex;
  align-items: flex-start;
  gap: 8px;
  margin-bottom: 12px;
}

.message-avatar {
  width: 36px;
  height: 36px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f5f5;
  border-radius: 50%;
}

.message-content {
  flex: 1;
  background: #f8f8f8;
  border-radius: 8px;
  padding: 12px;
  font-size: 14px;
  line-height: 1.4;
}

.user-message .message-content {
  background: #e0f7fa;
}

.ai-message .message-content {
  background: #f8f8f8;
}

.loading-tip {
  color: var(--text-color-secondary);
  font-size: 14px;
  margin-top: 8px;
}

.chat-input {
  padding: 16px;
  border-top: 1px solid #eee;
}

.message-field {
  width: 100%;
}

.send-button {
  margin-left: 8px;
}

.slide-up-enter-active,
.slide-up-leave-active {
  transition: transform 0.3s ease-in-out;
}

.slide-up-enter-from,
.slide-up-leave-to {
  transform: translateY(100%);
}

.slide-up-enter-to,
.slide-up-leave-from {
  transform: translateY(0);
}
</style>
